package com.fanshuai.soring.boot.webflux.metrics;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.reactive.handler.AbstractUrlHandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

public class ReactiveMetricsHandlerMapping extends AbstractUrlHandlerMapping {

    private ReactiveMetricsOutput metricsOutput;

    public ReactiveMetricsHandlerMapping(ReactiveMetricsOutput metricsOutput) {
        this.metricsOutput = metricsOutput;
    }

    @Override
    public Mono<Object> getHandlerInternal(ServerWebExchange exchange) {
        String uri = exchange.getRequest().getURI().getPath();
        String metricsHeader = getHeader("metrics", exchange);
        boolean metrics = uri.startsWith("/metrics") || StringUtils.isNotBlank(metricsHeader);

        if (metrics) {
            return Mono.just(metricsOutput);
        }
        return super.getHandlerInternal(exchange);
    }

    private String getHeader(String headerName, ServerWebExchange exchange) {
        List<String> metricsHeader = exchange.getRequest().getHeaders().get("metrics");
        return CollectionUtils.isEmpty(metricsHeader) ? null : metricsHeader.get(0);
    }
}
